<template>
  <div>
    <!-- 指标筛选 -->
    <el-row :gutter="20" style="margin-bottom: 20px; width: 90%">
      <el-col :span="4">
        <el-radio-group v-model="selectedIndicator" size="small">
          <el-radio-button label="so2Total">SO2超标累计</el-radio-button>
          <el-radio-button label="coTotal">CO超标累计</el-radio-button>
          <el-radio-button label="spmTotal">PM2.5超标累计</el-radio-button>
          <el-radio-button label="aqiTotal">AQI超标累计</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="4">
        <el-select v-model="selectedProvince" placeholder="选择省份" size="small" style="width: 100%">
          <el-option v-for="item in provinceList" :key="item.provinceId" :label="item.provinceName" :value="item.provinceId" />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" size="small" @click="highlightProvince">高亮显示</el-button>
      </el-col>
    </el-row>
    <!-- 地图容器 -->
    <div ref="mapRef" style="width: 100%; height: 700px;"></div>
    <!-- 省份详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="省份详情">
      <div v-if="detailData">
        <p>省份: {{ detailData.provinceName }}</p>
        <p>SO2超标累计: {{ detailData.so2Total }}</p>
        <p>CO超标累计: {{ detailData.coTotal }}</p>
        <p>PM2.5超标累计: {{ detailData.spmTotal }}</p>
        <p>AQI超标累计: {{ detailData.aqiTotal }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, inject, onMounted, onUnmounted, nextTick, onDeactivated, computed, watch } from "vue";
import * as echarts from "echarts";
import chinaJson from '@/assets/china.json';

// 从provide中注入axios
const axios = inject("axios");

// 数据状态
const provinceItemTotalArr = ref([]);
const provinceList = ref([]);
const selectedIndicator = ref("so2Total");
const selectedProvince = ref("");
const detailDialogVisible = ref(false);
const detailData = ref({});
const detailDataList = ref([]);

// 地图状态
const mapRef = ref(null);
let mapChart = null;
const mapLoading = ref(true);
const mapError = ref(false);
const mapContainerReady = ref(false);

// 新增：取消请求的控制器和清理函数
let abortController = null;
let currentCleanup = null;

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null;
  const debounced = function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
  debounced.cancel = () => clearTimeout(timer);
  return debounced;
};

// 初始化数据
const initData = async () => {
  if (abortController) {
    abortController.abort();
  }

  try {
    mapLoading.value = true;
    mapError.value = false;

    abortController = new AbortController();

    const tableResponse = await axios.get(
        "statistics/listProvinceItemTotalStatis",
        null,
        { signal: abortController.signal }
    );

    if (Array.isArray(tableResponse.data)) {
      provinceItemTotalArr.value = [...tableResponse.data];
      provinceList.value = provinceItemTotalArr.value.map(item => ({
        provinceId: item.provinceId,
        provinceName: item.provinceName
      }));

      if (mapRef.value && mapContainerReady.value) {
        initMap();
      }
    } else {
      console.error("API返回数据不是数组:", tableResponse.data);
      mapLoading.value = false;
      mapError.value = true;
    }
  } catch (error) {
    if (error.name === 'CanceledError') {
      console.log("请求被取消");
      return;
    }
    console.error("初始化失败:", error);
    mapLoading.value = false;
    mapError.value = true;
  }
};

// 初始化地图
const initMap = () => {
  console.log("initMap: mapRef =", mapRef.value);
  if (!isMounted || !mapRef.value || !mapContainerReady.value) {
    console.error("Map container not ready or component not mounted");
    mapLoading.value = false;
    mapError.value = true;
    return;
  }
  try {
    cleanupMap();
    mapChart = echarts.init(mapRef.value);
    echarts.registerMap('china', chinaJson);

    const seriesData = provinceItemTotalArr.value.map(item => ({
      name: item.provinceName,
      value: item[selectedIndicator.value] || 0,
      selected: item.provinceId === selectedProvince.value
    }));

    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}<br/>{c}'
      },
      visualMap: {
        min: 0,
        max: Math.max(...seriesData.map(item => item.value), 1),
        left: 'right',
        top: 'center',
        text: ['高', '低'],
        calculable: true,
        inRange: {
          color: ['#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695']
        }
      },
      series: [{
        name: '指标数据',
        type: 'map',
        map: 'china',
        label: {
          show: true,
          formatter: '{b}',
          color: '#333'
        },
        data: seriesData,
        emphasis: {
          label: { show: true },
          itemStyle: { areaColor: '#f00' }
        },
        itemStyle: {
          areaColor: '#ddd',
          borderColor: '#999'
        }
      }]
    };

    mapChart.setOption(option);

    // 点击事件：显示省份详细信息
    mapChart.on('click', (params) => {
      const provinceData = provinceItemTotalArr.value.find(item => item.provinceName === params.name);
      if (provinceData) {
        detailData.value = provinceData;
        detailDataList.value = [provinceData];
        detailDialogVisible.value = true;
      } else {
        console.warn(`未找到省份数据: ${params.name}`);
      }
    });

    const handleResize = debounce(() => {
      if (mapChart) mapChart.resize();
    }, 300);

    window.addEventListener('resize', handleResize);
    currentCleanup = () => window.removeEventListener('resize', handleResize);

    mapLoading.value = false;
    console.log("Map initialized successfully");
  } catch (error) {
    console.error("Map init failed:", error);
    mapLoading.value = false;
    mapError.value = true;
  }
};

// 安全更新地图
const safeUpdateMap = debounce(() => {
  if (!isMounted || !mapChart || !mapRef.value) {
    console.warn("Skipping map update: Component not mounted or map not ready");
    return;
  }
  try {
    const seriesData = provinceItemTotalArr.value.map(item => ({
      name: item.provinceName,
      value: item[selectedIndicator.value] || 0,
      selected: item.provinceId === selectedProvince.value
    }));

    mapChart.setOption({
      visualMap: { max: Math.max(...seriesData.map(item => item.value), 1) },
      series: [{ data: seriesData }]
    });
  } catch (error) {
    console.error("Map update failed:", error);
  }
}, 300);

// 清理地图资源
const cleanupMap = () => {
  if (mapChart) {
    mapChart.dispose();
    mapChart = null;
  }
  if (currentCleanup) {
    currentCleanup();
    currentCleanup = null;
  }
};

// 筛选数据
const filteredData = computed(() => {
  if (!Array.isArray(provinceItemTotalArr.value)) return [];
  if (selectedProvince.value) {
    return provinceItemTotalArr.value.filter(item => item.provinceId === selectedProvince.value);
  }
  return provinceItemTotalArr.value;
});

// 高亮显示选中省份
const highlightProvince = () => {
  if (!mapChart || !selectedProvince.value) return;

  const provinceName = provinceItemTotalArr.value.find(
      item => item.provinceId === selectedProvince.value
  )?.provinceName;

  if (provinceName) {
    mapChart.dispatchAction({
      type: 'highlight',
      name: provinceName
    });
  }
};

// 监听指标和省份选择变化
watch(selectedIndicator, safeUpdateMap);
watch(selectedProvince, safeUpdateMap);

// 生命周期管理
let isMounted = false;

onMounted(() => {
  isMounted = true;
  nextTick(() => {
    console.log("Mounted, mapRef =", mapRef.value);
    mapContainerReady.value = true;
    initData();
  });
});

onDeactivated(() => {
  safeUpdateMap.cancel();
  cleanupMap();
});

onUnmounted(() => {
  isMounted = false;
  if (abortController) abortController.abort();
  cleanupMap();
  mapContainerReady.value = false;
});
</script>
